//
// Created by wk on 2023/12/5.
//
#include <iostream>
#include "AudioConvert.h"


namespace test {


#pragma pack(1)

    struct WavHeader {
        char riff[4];
        unsigned int fileSize;
        char wave[4];
        char fmt[4];
        unsigned int fmtSize;
        unsigned short audioFormat;
        unsigned short numChannels;
        unsigned int sampleRate;
        unsigned int byteRate;
        unsigned short blockAlign;
        unsigned short bitsPerSample;
        char data[4];
        unsigned int dataSize;
    };

#pragma pop()


    /**
 * 生成wav 生成 s16le pcm数据
 */
    void static wav_to_pcm_test() {


        FILE *mp3File = fopen("D:\\audio\\houlai.wav", "rb");


        WavHeader header;
        memset(&header, 0, sizeof(header));
        fread(&header, sizeof(header), 1, mp3File);


        FILE *pcm_16 = fopen("D:\\audio\\houlai17.pcm", "wb");

        char buffer[1024];
        size_t bytesRead;
        while ((bytesRead = fread(buffer, 1, sizeof(buffer), mp3File)) > 0) {
            fwrite(buffer, bytesRead, 1, pcm_16);
        }

        fclose(mp3File);
        fclose(pcm_16);
    }

    /**
 *  16pcm 转 float pcm
 */
    void pcm16_to_floatpcm_test() {


        FILE *pcm_16file = fopen("D:\\audio\\houlai_s16.pcm", "rb");

        FILE *pcm_f32file = fopen("D:\\audio\\houlai_f32.pcm", "wb");

        char buffer[1024];
        size_t bytesRead;
        float float_buffer[1024 * 4];
        while ((bytesRead = fread(buffer, 1, sizeof(buffer), pcm_16file)) > 0) {
            audio::AudioConvert::convert_signed16_tof32((int16_t *) buffer, bytesRead / 2,
                                                        float_buffer);
            fwrite(float_buffer, bytesRead / 2 * sizeof(float), 1, pcm_f32file);
        }

        fclose(pcm_16file);
        fclose(pcm_f32file);

    }

    /**
     * 从f32pcm转s16pcm
     */
    void floatpcm_to_pcm16_test() {


        FILE*  pcm_f32file = fopen("D:\\audio\\houlai_f32.pcm", "rb");

        FILE *pcm_16file = fopen("D:\\audio\\houlai_f16_2.pcm", "wb");

        float input_buffer[1024];
        size_t bytesRead;
        int16_t out_buffer[1024];
        while ((bytesRead = fread(input_buffer, sizeof(float), sizeof(input_buffer)/sizeof(float), pcm_f32file)) > 0)
        {
            //convert_signed16_tof32((int16_t*)buffer, bytesRead / 2, float_buffer);
            //fwrite(float_buffer, bytesRead / 2 * sizeof(float), 1, pcm_16file);

            audio::AudioConvert::convert_f32_to_signed16(input_buffer, bytesRead, out_buffer);
            fwrite(out_buffer, bytesRead * sizeof(int16_t), 1, pcm_16file);
        }


        fclose(pcm_f32file);
        fclose(pcm_16file);

    }
}